#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    this->setFixedSize(400, 400);
}

Widget::~Widget()
{
    delete ui;
}

void Widget::GernerateQRCode(const QString &text, QPixmap &qrPixmap, int scale)
{
    if(text.isEmpty())
    {
        return;
    }

    //二维码数据
    QRcode *qrCode = nullptr;

    //这里二维码版本传入参数是2,实际上二维码生成后，它的版本是根据二维码内容来决定的
    qrCode = QRcode_encodeString(text.toStdString().c_str(), 2,
                                 QR_ECLEVEL_H, QR_MODE_8, 1);

    if(nullptr == qrCode)
    {
        return;
    }

    int qrCode_Width = qrCode->width > 0 ? qrCode->width : 1;

    //qDebug() << qrCode_Width;
    int width = scale * qrCode_Width;
    int height = scale * qrCode_Width;

    QImage image(width, height, QImage::Format_RGB32);

    QPainter mPainter(&image);
    QColor background(Qt::white);
    mPainter.setBrush(background);
    mPainter.setPen(Qt::NoPen);
    mPainter.drawRect(0, 0, width, height);
    QColor foreground(Qt::black);
    mPainter.setBrush(foreground);

    for(int y = 0; y < qrCode_Width; ++y)
    {
        for(int x = 0; x < qrCode_Width; ++x)
        {
            unsigned char character = qrCode->data[y * qrCode_Width + x];

            if(character & 0x01)
            {
                QRect rect(x * scale, y * scale, scale, scale);
                mPainter.drawRects(&rect, 1);
            }
        }
    }

    qrPixmap = QPixmap::fromImage(image);
    QRcode_free(qrCode);
}


void Widget::on_pushButton_clicked()
{
    QPixmap qrPixmap;
    int width = ui->label->width();
    int height = ui->label->height();
    GernerateQRCode(ui->lineEdit->text(), qrPixmap, 10);
    qrPixmap = qrPixmap.scaled(QSize(width, height),
                               Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    ui->label->setPixmap(qrPixmap);
    qrPixmap.save("qrencode.jpg", nullptr, -1); //这里直接就保存为图片
}
